package com.boesch.electroOffice.utils;

import java.io.IOException;
import java.util.Map;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.portlet.PortletContext;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.portlet.PortletSession;
import javax.portlet.ReadOnlyException;
import javax.portlet.ValidatorException;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;

public class PortletUtils {
	
	private static final Log log = LogFactoryUtil.getLog(PortletUtils.class);

	public static PortletSession getPortletSession() {
		PortletSession portletSession = PortletSession.class.cast(getExternalContext().getSession(false));
		return portletSession;
	}
	
	public static String getSessionAttribute(String key) {
		PortletSession session = PortletUtils.getPortletSession();
		return String.valueOf(session.getAttribute(key));
	}
	
	public static void setSessionAttribute(String key, String value) {
		PortletSession session = PortletUtils.getPortletSession();
		session.setAttribute(key, value);
	}
	
	public static PortletContext getPortletContext() {
		return PortletUtils.getPortletSession().getPortletContext();
	}
	
	public static ExternalContext getExternalContext() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		return facesContext.getExternalContext();
	}

	public static PortletPreferences getPortletPreferences() {
		PortletRequest portletRequest = getPortletRequest();
		return portletRequest.getPreferences();
	}
	
	public static PortletRequest getPortletRequest() {
		return PortletRequest.class.cast(getExternalContext().getRequest());
	}
	
	public static String getRequestParameter(String key) {
		Map<String,String> params = getExternalContext().getRequestParameterMap();
		String parameter = params.get(key);
		return parameter;
	}
	
	public static String getPortletPreference(String preferenceName, String defaultValue){
		return PortletUtils.getPortletPreferences().getValue(preferenceName, defaultValue);
	}

	public static void setPortletPreference(String preferenceName, String preferenceValue){
		PortletPreferences portletPreferences = PortletUtils.getPortletPreferences();
		try {
			portletPreferences.setValue(preferenceName, preferenceValue);
			portletPreferences.store();
		} catch (ReadOnlyException e) {
			log.error("Error on setting " + preferenceName, e);
		} catch (ValidatorException e) {
			log.error("Error on setting " + preferenceName, e);
		} catch (IOException e) {
			log.error("Error on setting " + preferenceName, e);
		}
	}
}
